import React, { Component } from "react";
import { Input, Icon, Radio, Checkbox } from "antd";
import "./index.less";
import { getTreeperBydepart } from "../../services/api";

const { Search } = Input;
const RadioGroup = Radio.Group;

class SelectUser extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      searchvalue: "",
      radiovalue: this.props.value || "",
      type: this.props.type || "checkbox",
      currentTree: [],
      checkboxValueArr: this.props.value || [],
      navtree: [{ title: "", key: "all", children: [] }],
      alluser: this.allUser,
      visible: false
    };
  }

  componentDidMount() {
    console.log(this.props.value, "this.props.value-selectuser");
    this.getPersonData();
  }

  //从api中获取获取数据的接口
  getPersonData = () => {
    getTreeperBydepart({}).then(response => {
      //无参请求
      console.log("获取人员树的数据结构", response);
      if (response.data) {
        this.initData(response.data);
        const val =
          this.state.type === "checkbox"
            ? this.state.checkboxValueArr
            : this.state.radiovalue;
        console.log(val, "init-val");
        this.propsOnselect(val);
      }
    });
  };

  //初始化数据
  initData = data => {
    this.generatorAllUser(data);
    if (data.length > 0) {
      const ret = data;
      this.setState({
        currentTree: ret[0]["children"],
        navtree: [
          {
            title: ret[0]["title"],
            key: ret[0]["key"],
            children: ret[0]["children"]
          }
        ]
      });
    }
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.value instanceof Array) {
      this.setState({ checkboxValueArr: nextProps.value });
    }

    if (nextProps.visible !== this.state.visible) {
      this.setState({ visible: nextProps.visible });
    }

    if (nextProps.visible) {
      this.setState({ searchvalue: "" });
    }

    if (typeof nextProps.value === "string") {
      this.setState({ radiovalue: nextProps.value });
      // this.propsOnselect(nextProps.value);
      if (nextProps.value !== this.state.radiovalue) {
        this.propsOnselect(nextProps.value);
      }
    }
  }

  /* 暂无人员 */
  nobody = () => {
    return <div className="nobody">暂无结果</div>;
  };

  propsOnselect = value => {
    console.log(value, "propsOnselect1");
    // console.log(JSON.stringify(this.allUser), "this.allUser");
    const arrayObj = [];
    if (value instanceof Array) {
      value.forEach(val => {
        const ret = this.allUser.find(val1 => {
          return val1.key === val;
        });
        if (ret) {
          arrayObj.push(ret);
        }
      });
    } else {
      const ret = this.allUser.find(val1 => {
        return val1.key === value;
      });
      if (ret) {
        arrayObj.push(ret);
      }
    }

    this.props.onSelect(value, arrayObj);
  };

  allUser = [];
  /* 遍历所有人员用做搜索 */
  generatorAllUser = data => {
    data.forEach(val => {
      if (val.treeType === "2") {
        if (this.allUser.indexOf(val) === -1) {
          this.allUser.push(val);
        } else {
          console.log(val, "generatorAllUser");
        }
      }
      if (val.treeType === "1") {
        if (val.children !== null) {
          this.generatorAllUser(val.children);
        }
      }
    });
  };

  //面包屑
  renderNavBar = () => {
    const { navtree } = this.state;
    return (
      <div className="nav-partment">
        {navtree.map((val, index) => {
          if (navtree.length - 1 !== index) {
            return (
              <span
                key={index}
                onClick={() => {
                  const navtreenew = navtree.slice(0, index + 1);
                  this.setState({
                    navtree: navtreenew,
                    currentTree: val.children
                  });
                }}
                className="nav"
              >
                {val.title}
                <Icon type="right" />
              </span>
            );
          }

          return <span key={index}>{val.title}</span>;
        })}
      </div>
    );
  };
  /* 搜索 */

  rendeSearchRadio = () => {
    const userlist = this.state.alluser.filter(val => {
      const param = val;
      if (val.title.indexOf(this.state.searchvalue) !== -1) {
        param.show = "block";
      } else {
        param.show = "none";
      }
      return param;
    });
    if (
      userlist.some(val => {
        return val.show === "block";
      })
    ) {
      return (
        <RadioGroup
          onChange={e => {
            this.setState({ radiovalue: e.target.value });
            this.propsOnselect(e.target.value);
          }}
          value={this.state.radiovalue}
        >
          {userlist.map((val, index) => {
            if (val.treeType === "2") {
              return (
                <Radio
                  key={index}
                  style={{ display: val.show }}
                  className="radioStyle"
                  value={val.key}
                >
                  <i className="usericon" />
                  {val.title}
                </Radio>
              );
            }
            return "";
          })}
          <Radio
            style={{ display: "none" }}
            key="null"
            className="radioStyle"
            value="null"
          >
            无值
          </Radio>
        </RadioGroup>
      );
    } else {
      return this.nobody();
    }
  };

  renderSearchChecked = () => {
    const userlist = this.state.alluser.map(val => {
      const param = { ...val };
      if (val.title.indexOf(this.state.searchvalue) !== -1) {
        param.show = "block";
      } else {
        param.show = "none";
      }
      return param;
    });
    if (
      userlist.some(val => {
        return val.show === "block";
      })
    ) {
      return (
        <Checkbox.Group
          onChange={value => {
            this.setState({ checkboxValueArr: value });
            this.propsOnselect(value);
          }}
          value={this.state.checkboxValueArr}
        >
          {userlist.map((val, index) => {
            if (val.treeType === "2") {
              return (
                <Checkbox
                  style={{ display: val.show }}
                  key={index}
                  className="radioStyle"
                  value={val.key}
                >
                  <i className="usericon" />
                  {val.title}
                </Checkbox>
              );
            }
            return "";
          })}
        </Checkbox.Group>
      );
    } else {
      return this.nobody();
    }
  };

  /* 无搜索 */
  renderDepartment = () => {
    return this.state.currentTree.map((val, index) => {
      if (val.treeType === "1") {
        return (
          <div key={index} className="department-item">
            <i className="departmenticon" />
            {val.title}
            <span
              onClick={() => {
                const navtree = this.state.navtree.slice();
                navtree.push({
                  title: val.title,
                  key: val.key,
                  children: val.children
                });
                this.setState({
                  currentTree: val.children ? val.children : [],
                  navtree
                });
              }}
              className="lower"
            >
              <i className="lowevericon" />下级
            </span>
          </div>
        );
      }
      return "";
    });
  };

  renderRadio = () => {
    const currentTree = this.state.currentTree.slice();
    const alluser = this.state.alluser.slice();
    const userlist = alluser.map(val => {
      const param = val;
      param.show = "none";
      currentTree.forEach((val1, index) => {
        if (val1.key === val.key) {
          param.show = "block";
          currentTree.splice(index, 1);
        }
      });
      return param;
    });

    return (
      <RadioGroup
        onChange={e => {
          this.setState({ radiovalue: e.target.value });
          this.propsOnselect(e.target.value);
        }}
        value={this.state.radiovalue}
      >
        {userlist.map((val, index) => {
          if (val.treeType === "2") {
            return (
              <Radio
                style={{ display: val.show === "block" ? val.show : "none" }}
                key={index}
                className="radioStyle"
                value={val.key}
              >
                <i className="usericon" />
                {val.title}
              </Radio>
            );
          }
          return "";
        })}
        <Radio
          style={{ display: "none" }}
          key="null"
          className="radioStyle"
          value="null"
        >
          无值
        </Radio>
      </RadioGroup>
    );
  };

  renderChecked = () => {
    const currentTree = this.state.currentTree.slice();
    const alluser = this.state.alluser.slice();
    const userlist = alluser.map(val => {
      const param = val;
      param.show = "none";
      currentTree.forEach((val1, index) => {
        if (val1.key === val.key) {
          param.show = "block";
          currentTree.splice(index, 1);
        }
      });
      return param;
    });

    return (
      <Checkbox.Group
        onChange={value => {
          console.log(value, "Checkbox-value");
          this.setState({ checkboxValueArr: value });
          this.propsOnselect(value);
        }}
        value={this.state.checkboxValueArr}
      >
        {userlist.map(val => {
          if (val.treeType === "2") {
            return (
              <Checkbox
                style={{ display: val.show === "block" ? val.show : "none" }}
                key={val.key}
                className="radioStyle"
                value={val.key}
              >
                <i className="usericon" />
                {val.title}
              </Checkbox>
            );
          }
          return "";
        })}
      </Checkbox.Group>
    );
  };

  render() {
    const { navtree } = this.state;
    return (
      <div className="SelectUser">
        <Search
          placeholder="请输入搜索内容"
          value={this.state.searchvalue}
          onChange={e => {
            this.setState({
              searchvalue: e.target.value,
              navtree: navtree.slice(0, 1),
              currentTree: navtree[0].children
            });
          }}
          onSearch={value => console.log(value)}
        />
        {!this.state.searchvalue && this.renderNavBar()}
        <div className="list">
          {this.state.searchvalue.trim().length === 0 &&
            this.renderDepartment()}
          {this.state.type === "radio" &&
          this.state.searchvalue.trim().length === 0
            ? this.renderRadio()
            : ""}
          {this.state.type === "checkbox" &&
          this.state.searchvalue.trim().length === 0
            ? this.renderChecked()
            : ""}
          {/* 搜索结果 */}
          {this.state.searchvalue.trim().length > 0 &&
          this.state.type === "radio"
            ? this.rendeSearchRadio()
            : ""}
          {this.state.searchvalue.trim().length > 0 &&
          this.state.type === "checkbox"
            ? this.renderSearchChecked()
            : ""}
        </div>
      </div>
    );
  }
}

export default SelectUser;
